package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.constant.CacheConstant;
import com.atguigu.spzx.manager.mapper.SysRoleMapper;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.AssginRoleDto;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysRole;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;


    @Autowired
    SysRoleMapper sysRoleMapper;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {
        //---------验证码校验 开始------------------------------------------------------------------
        String captcha = loginDto.getCaptcha(); //用户输入校验码
        String codeKey = loginDto.getCodeKey(); //redis中存储校验码的key

        String validateCodeFromRedis = redisTemplate.opsForValue().get(CacheConstant.USER_LOGIN_VALIDATECODE_PREFIX + codeKey);

        if (!StringUtils.hasText(validateCodeFromRedis) || !StrUtil.equalsIgnoreCase(captcha, validateCodeFromRedis)) {
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        redisTemplate.delete(CacheConstant.USER_LOGIN_VALIDATECODE_PREFIX + codeKey);

        //---------验证码校验 结束------------------------------------------------------------------

        //1.根据用户名称查询用户
        SysUser sysUesr = sysUserMapper.selectByUsername(loginDto.getUserName());
        if (sysUesr == null) {
            //throw new RuntimeException("用户名称或密码错误");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //2.密码校验
        /**
         * MD5: 特点
         *  1.不可逆算法，只能加密，不能解密
         *  2.加密后长度固定。16字节。 一般数据库存储转换字符串。将一个字节分成高四位和低四位。四位数范围 0~15   一个字节转换为2个16进制数。
         *  3.原文不变，密文不变。
         *  主要用途：数据传输过程中，校验数据不被篡改。
         */
        String inputPassword = loginDto.getPassword(); //明文密码
        String md5DbPassword = sysUesr.getPassword(); //数据库中用户密码

        String inputPasswordmd5 = DigestUtils.md5DigestAsHex(inputPassword.getBytes());

        if (!md5DbPassword.equalsIgnoreCase(inputPasswordmd5)) {
            //throw new RuntimeException("用户名称或密码错误");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //3.生成令牌：将令牌返回前端，以及将令牌作为key,用户信息作为值，存储在redis中。 TODO 临时有效时间
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(CacheConstant.USER_LOGIN_PREFIX + token, JSON.toJSONString(sysUesr), 3000, TimeUnit.MINUTES); //将来需要在每次访问系统功能时，刷新时间。

        //4.封装LoginVo
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        return loginVo;
    }

/*    @Override
    public SysUser getUserInfo(String token) {
        String sysUserJsonStr = redisTemplate.opsForValue().get(CacheConstant.USER_LOGIN_PREFIX+token);
        if(StringUtils.hasText(sysUserJsonStr)){
            SysUser sysUser = JSON.parseObject(sysUserJsonStr,SysUser.class);
            sysUser.setPassword(null); //密码擦除
            return sysUser;
        }
        return null;
    }*/

    @Override
    public SysUser getUserInfo(String token) {
        SysUser sysUser = AuthContextUtil.get();
        sysUser.setPassword(null); //密码擦除
        return sysUser;
    }


    @Override
    public void logout(String token) {
        redisTemplate.delete(CacheConstant.USER_LOGIN_PREFIX + token);
    }


    @Override
    public PageInfo<SysUser> findPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum,pageSize); //  pageNum,pageSize  =>>   Page

        List<SysUser> list = sysUserMapper.findPage(sysUserDto); //  Page extends ArrayList

        return new PageInfo<SysUser>(list);
    }


    @Override
    public void save(SysUser sysUser) {
        sysUser.setStatus(1); //状态（1：正常 0：停用）
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        sysUserMapper.insert(sysUser);
    }

    @Override
    public SysUser getById(Long id) {
        return sysUserMapper.getById(id);
    }

    @Override
    public void update(SysUser sysUser) {
        sysUserMapper.update(sysUser);
    }

    @Override
    public void deleteById(Long id) {
        sysUserMapper.deleteById(id);
    }

    @Override
    public Map<String, Object> findRoleByUserId(Long id) {

        //1.查询所有角色
        List<SysRole> allRoles = sysRoleMapper.selectAll();

        //2.查询当前用户所拥有的角色id集合
        List<Long> userRoleIds = sysRoleMapper.selectRoleIdsByUserId(id);

        Map<String, Object> data = new HashMap<>();
        data.put("allRoles",allRoles);
        data.put("userRoleIds",userRoleIds);
        return data;
    }

    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        Long userId = assginRoleDto.getUserId();
        //先删除旧的关系数据
        sysUserMapper.deleteUserRoleRelationship(userId);

        //重新保存新的关系数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        if(!CollectionUtils.isEmpty(roleIdList)){
            for (Long roleId : roleIdList) {
                sysUserMapper.insertUserRoleRelationship(roleId,userId);
            }
        }
    }
}
